<?php

namespace App\Admin\Http\Middleware;

use Closure;
use App\Admin\Eloquent\Role;
use Illuminate\Auth\Access\AuthorizationException;
    
class RoleBasedAccessControl extends Middleware
{
    /**
     * 处理传入的请求
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // $routes = \Route::getRoutes()->getRoutes();

        // foreach ($routes as $route) {
        //     if (preg_match ('/^admin*/', $route->getUri())) {
        //         $perm = new \App\Admin\Eloquent\Permission();
        //         $perm->name = $route->getUri();
        //         $perm->methods = implode('|', $route->getMethods());
        //         $perm->uri = $route->getUri();

        //         $perm->save();
        //     }
        // }
        // 角色集合

        $roles = collect();

        // 游客角色
        if($role=Role::guest()){
            $roles->push($role);
        }

        if ($user = $this->getLoginUser($request)) {
            $roles = $roles->merge($user->cachedRoles());
        }

        foreach ($roles as $role) {
            if ($role->hasPermission($this->permission($request))) {
                return $next($request);
            }
        }

        throw new AuthorizationException('Not Authorization');
    }

    /**
     * 访问权限
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function permission($request)
    {
        $methods = implode('|', $request->route()->getMethods());

        $uri = $request->route()->getUri();

        return $methods . $uri;
    }
}
